import { recordInitAssignAccount, recordInitTree, registrationInfoInit, saveTravgelArrangment } from '@/services/api/api-interview-record';
import { AudioOutlined, CarOutlined, PlusOutlined, SendOutlined, SnippetsOutlined, UserOutlined } from '@ant-design/icons';
import {
    DrawerForm,
    FormListActionType,
    ModalForm,
    ProCard,
    ProForm,
    ProFormCascader,
    ProFormDatePicker,
    ProFormDateRangePicker,
    ProFormGroup,
    ProFormInstance,
    ProFormList,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Cascader, Form, message } from 'antd';
import moment from 'moment';
import React, { useEffect } from 'react';
import { useRef, useState } from 'react';

interface AddTravelArrangementsProps {
    onRefurbish: () => void;
    planList: InterviewRecordData.planList;
    registrationInfo: InterviewRecordData.RegistrationInfo;
    id: string;
}
const AddTravelArrangements: React.FC<AddTravelArrangementsProps> = ({ onRefurbish, id, planList, registrationInfo }) => {
    const planActionRef = useRef<FormListActionType<{ name: string; }>>();

    const formRef = useRef<ProFormInstance>();
    const assignOrganizationRef = useRef<FormListActionType<{ name: string; }>>();
    const [activeKeys, setActiveKeys] = useState({}); // 存储每个出行安排的activeKey状态
    const [tabKeys, setTabKeys] = useState(['cars', 'media', 'organization']);
    const [mediaOptions, setMediaOptions] = useState();
    const [organizationOptions, setOrganizationOptions] = useState();

    const [tab, setTab] = useState('cars');

    /**
      * 预备Tree结构数据
      * @param data
      */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    // children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }

    /**
       * 加载 媒体单位
       */
    const loadInitMediaOptions = async () => {
        try {
            const response = await recordInitTree({ type: 0 });
            if (response.code === 0) {
                setMediaOptions(readyTreeData(response.data));
            }
        } catch (error) { }
    };
    /**
     * 加载 采访单位
     */
    const loadInitAssignOrganizationOptions = async () => {
        try {
            const response = await recordInitTree({ type: 1 });
            if (response.code === 0) {
                setOrganizationOptions(readyTreeData(response.data));
            }
        } catch (error) { }
    };

    const handleTabChange = (index, key) => {
        setActiveKeys(prev => ({
            ...prev,
            [index]: key, // 更新对应出行安排的activeKey  
        }));
    };



    return (
        <DrawerForm
            title="出行安排"
            trigger={
                <Button type="primary" style={{
                    background: '#87d068',
                }}>
                    <SendOutlined />
                    出行安排
                </Button>
            }
            formRef={formRef}
            autoFocusFirstInput
            drawerProps={{
                destroyOnClose: true,
            }}
            submitTimeout={2000}
            onFinish={async (values) => {

                // if (Array.isArray(values.planList)) {
                //     values.planList = values.planList.map(item => {
                //         console.log(item.mediaList);
                //         if (Array.isArray(item.mediaList)) {
                //             item.mediaList.map((item1) => {
                //                 if (Array.isArray(item1.reporterListAdd)) {
                //                     item1.reporterList.push(...item1?.reporterListAdd)
                //                 }
                //                 return item1
                //             })
                //         }
                //         return item;
                //     });
                // }
                const res = await saveTravgelArrangment({
                    recordId: id,
                    ...values
                })
                if (res.code === 0) {
                    message.success('提交成功');
                    onRefurbish()
                    return true;
                } else {
                    message.error('提交失败');
                }
                onRefurbish()
            }}
            onOpenChange={(visible) => {
                if (visible) {
                    //加载选择媒体
                    loadInitMediaOptions()
                    loadInitAssignOrganizationOptions()
                }
            }}
        >

            <ProFormList
                min={1}
                actionRef={planActionRef}
                name="planList"
                initialValue={
                    Array.isArray(planList) && planList.length > 0 ? planList : registrationInfo.length > 0 ? registrationInfo : [{ leader: '' }]  // 默认情况，确保始终有一行显示  
                }
                label={<div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                    <span style={{ fontSize: 16 }}><SnippetsOutlined style={{ marginRight: 5 }} />出行安排</span>
                    <Button
                        type="primary"
                        style={{ display: 'flex', justifyContent: 'flex-end' }}
                        onClick={() => {
                            planActionRef.current?.add(registrationInfo[0]);
                        }}
                    >
                        添加出行安排
                    </Button>
                </div>}
                actionGuard={{
                    beforeAddRow: async (defaultValue, insertIndex) => {
                        return new Promise((resolve) => {
                            console.log(defaultValue, insertIndex);
                            setTimeout(() => resolve(true), 500);
                        });
                    },
                    beforeRemoveRow: async (index) => {
                        return new Promise((resolve) => {
                            if (index === 0) {
                                message.error('这行不能删');
                                resolve(false);
                                return;
                            }
                            setTimeout(() => resolve(true), 500);
                        });
                    },
                }}
                // creatorButtonProps={false}
                creatorRecord={registrationInfo[0]}
                creatorButtonProps={{
                    creatorButtonText: '添加出行安排',
                }}
                itemRender={({ listDom, action }, { index }) => {
                    const currentActiveKey = activeKeys[index] || tabKeys[0];
                    const planIndex = index;
                    const carsActionRef = useRef<FormListActionType<{ name: string; }>>();
                    const mediaActionRef = useRef<FormListActionType<{ name: string; }>>();
                    const intervieweeRef = useRef<FormListActionType<{ name: string; }>>();
                    return (
                        <ProCard
                            bordered
                            extra={action}
                            title={`出行安排${index + 1}`}
                            style={{
                                marginBlockEnd: 8,
                                display: 'flex',
                                flexDirection: 'column'
                            }}
                        >
                            <ProFormGroup key="group">
                                <ProFormText name="leader" label="带队人员" width="sm" />
                                <ProFormText
                                    width="sm"
                                    name="phone"
                                    label="联系电话"
                                    rules={[
                                        {
                                            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                            message: '请输入正确的手机号'
                                        }
                                    ]}
                                />
                                <ProFormDatePicker
                                    name="travelTime"
                                    width="sm"
                                    label="集中采访时间"
                                    fieldProps={{
                                        // disabledDate: (current) => current && current < moment().endOf('day'),
                                        format: 'YYYY-MM-DD HH:mm:ss',
                                    }}
                                />
                                <ProFormText
                                    name="address"
                                    label="采访地点"
                                    width="sm"
                                />

                            </ProFormGroup>
                            <ProFormDatePicker
                                name="presentationTime"
                                width="lg"
                                label="发布会时间"
                                fieldProps={{
                                    // disabledDate: (current) => current && current < moment(Array.isArray(formRef.current?.getFieldsValue()?.planList) && formRef.current?.getFieldsValue()?.planList[index].travelTime),
                                    format: 'YYYY-MM-DD HH:mm:ss',
                                }}
                            />
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                                <ProCard
                                    tabs={{
                                        activeKey: currentActiveKey,
                                        items: [
                                            {
                                                label: <span><UserOutlined />采访对象</span>,
                                                key: 'organization',
                                            },
                                            {
                                                label: <span><AudioOutlined />媒体信息</span>,
                                                key: 'media',
                                            },
                                            {
                                                label: <span><CarOutlined />车辆安排</span>,
                                                key: 'cars',
                                            },
                                        ],
                                        onChange: (key) => handleTabChange(index, key), // 处理选项卡变化  
                                    }}
                                />
                                {currentActiveKey === 'cars' && <ProFormList
                                    min={1}
                                    style={{ paddingInline: 10 }}
                                    name="carsList"
                                    actionRef={carsActionRef}
                                    label={<div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                                        <span><CarOutlined style={{ marginRight: 5 }} />车辆信息</span>
                                        <Button
                                            type="primary"
                                            style={{ display: 'flex', justifyContent: 'flex-end' }}
                                            onClick={() => {
                                                const list = carsActionRef.current?.getList();
                                                carsActionRef.current?.add({
                                                    name: '',
                                                });

                                            }}
                                        >
                                            添加车辆信息
                                        </Button>
                                    </div>}
                                    initialValue={[
                                        {
                                            name: '',
                                        },
                                    ]}
                                    creatorButtonProps={false}
                                    actionGuard={{
                                        beforeRemoveRow: async (index) => {
                                            return new Promise((resolve) => {
                                                if (index === 0) {
                                                    message.error('这行不能删');
                                                    resolve(false);
                                                    return;
                                                }
                                                setTimeout(() => resolve(true), 500);
                                            });
                                        },
                                    }}
                                    itemContainerRender={(doms) => {
                                        return <ProForm.Group>{doms}</ProForm.Group>;
                                    }}
                                >

                                    {(f, index, action) => {
                                        return (
                                            <>
                                                <ProFormText name="number" label="车牌" width="sm" />
                                                <ProFormText name="name" label="司机" width={120} />
                                                <ProFormText
                                                    name="phone"
                                                    label="电话"
                                                    rules={[
                                                        {
                                                            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                                            message: '请输入正确的手机号'
                                                        }
                                                    ]}
                                                />
                                            </>
                                        );
                                    }}
                                </ProFormList>}

                                {currentActiveKey === 'media' && <ProFormList
                                    min={1}
                                    style={{ paddingInline: 10 }}
                                    name="mediaList"
                                    // creatorButtonProps={false}
                                    creatorButtonProps={{
                                        creatorButtonText: '添加媒体信息',
                                    }}
                                    label={
                                        <div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                                            <span><AudioOutlined style={{ marginRight: 5 }} />媒体信息</span>
                                            <Button
                                                type="primary"
                                                style={{ display: 'flex', justifyContent: 'flex-end' }}
                                                onClick={() => {
                                                    mediaActionRef.current?.add({
                                                        name: '',
                                                        reporterList: [{ name: '' }],
                                                    });
                                                }}
                                            >
                                                添加媒体信息
                                            </Button>
                                        </div>
                                    }
                                    actionRef={mediaActionRef}
                                    // initialValue={Array.isArray(mediaInfo) && mediaInfo.length > 0 ? mediaInfo : [{ name: '', reporterList: [{ name: '' }] }]}
                                    itemRender={({ listDom, action }, { index }) => {
                                        // const reporterActionRef = React.useRef(); // 为每个媒体条目创建新的 actionRef  
                                        const reporterActionRef = useRef<FormListActionType<{ name: string; }>>();
                                        const reporterActionRefAdd = useRef<FormListActionType<{ name: string; }>>();
                                        // 处理单位更改，清空记者信息  
                                        let count = 1
                                        const handleOrganizationChange = (value) => {
                                            // // 清空当前记者列表  
                                            const list = planActionRef.current?.getList()

                                            const reporterList = list[planIndex].mediaList[index].reporterList;
                                            if (reporterList && reporterList.length > 0) {
                                                for (let index = 0; index <= reporterList.length; index++) {
                                                    reporterActionRef.current?.remove?.(0)
                                                }
                                                reporterActionRefAdd.current?.add({ // 使用独立的 actionRef  
                                                    name: '',
                                                });
                                            } else {
                                                console.log(value, count);
                                                count++
                                                if (count > 1) {

                                                } else {
                                                    reporterActionRefAdd.current?.add({ // 使用独立的 actionRef  
                                                        name: '',
                                                    })
                                                }
                                            }
                                        };
                                        return (
                                            <ProCard
                                                bordered
                                                extra={action}
                                                title={`媒体${index + 1}`}
                                                style={{
                                                    marginBlockEnd: 8,
                                                }}
                                            >
                                                {listDom}
                                                <ProFormSelect
                                                    width="lg"
                                                    label="单位"
                                                    name="organizationId"
                                                    showSearch
                                                    placeholder="选择单位"
                                                    options={mediaOptions}
                                                    // disabled
                                                    onChange={handleOrganizationChange} // 修改单位时清空记者信息
                                                />
                                                <ProFormList
                                                    name="reporterList"
                                                    actionRef={reporterActionRef} // 使用独立的 actionRef  
                                                    creatorButtonProps={false}
                                                    label={
                                                        <div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                                                            <span style={{ fontSize: 16 }}>记者信息</span>
                                                            <Button
                                                                type="primary"
                                                                style={{ display: 'flex', justifyContent: 'flex-end' }}
                                                                onClick={() => {
                                                                    reporterActionRefAdd.current?.add({ // 使用独立的 actionRef  
                                                                        name: '',
                                                                    });
                                                                }}
                                                            >
                                                                添加记者信息
                                                            </Button>
                                                        </div>
                                                    }
                                                >
                                                    <ProFormGroup key="group">
                                                        <ProFormText
                                                            name="name"
                                                            label="姓名"
                                                            width={120}
                                                            placeholder="请输入姓名"
                                                            disabled
                                                        />
                                                        <ProFormText
                                                            name="phone"
                                                            label="电话"
                                                            placeholder="请输入电话"
                                                            rules={[
                                                                {
                                                                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                                                    message: '请输入正确的手机号'
                                                                }
                                                            ]}
                                                        />
                                                    </ProFormGroup>
                                                </ProFormList>
                                                <ProFormList
                                                    name="reporterListAdd"
                                                    actionRef={reporterActionRefAdd} // 使用独立的 actionRef  
                                                    creatorButtonProps={false}
                                                >
                                                    <ProFormGroup key="group">
                                                        <ProFormText
                                                            name="name"
                                                            label="姓名"
                                                            width={120}
                                                            placeholder="请输入姓名"
                                                            required rules={[{ required: true, message: '姓名不能为空' }]}
                                                        />
                                                        <ProFormText
                                                            name="phone"
                                                            label="电话"
                                                            placeholder="请输入电话"
                                                            rules={[
                                                                {
                                                                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                                                    message: '请输入正确的手机号'
                                                                }
                                                            ]}
                                                        />
                                                    </ProFormGroup>
                                                </ProFormList>
                                            </ProCard>
                                        );
                                    }}
                                />}
                                {currentActiveKey === 'organization' && <ProFormList
                                    min={1}
                                    style={{ paddingInline: 10 }}
                                    name="assignOrganizationList"
                                    // creatorButtonProps={false}
                                    creatorButtonProps={{
                                        creatorButtonText: '添加采访对象',
                                    }}
                                    label={<div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                                        <span><UserOutlined style={{ marginRight: 5 }} />采访对象</span>
                                        <Button
                                            type="primary"
                                            style={{ display: 'flex', justifyContent: 'flex-end' }}
                                            onClick={() => {
                                                const list = intervieweeRef.current?.getList();
                                                intervieweeRef.current?.add({
                                                    name: '',
                                                    organizationList: []
                                                });
                                            }}
                                        >
                                            添加采访对象
                                        </Button>
                                    </div>}
                                    actionRef={intervieweeRef}
                                    // initialValue={Array.isArray(planList[index].assignOrganizationList) && planList[index].assignOrganizationList.length > 0 ? planList[index].assignOrganizationList : [{ name: '', organizationList: [{ name: '' }] }]}
                                    itemRender={({ listDom, action }, { index }) => {
                                        const assignOrganizationRef = useRef<FormListActionType<{ name: string; }>>();
                                        const assignOrganizationRefAdd = useRef<FormListActionType<{ name: string; }>>();
                                        // 处理单位更改，清空记者信息  
                                        const handleOrganizationChange = (value) => {
                                            // // 清空当前记者列表  
                                            const list = planActionRef.current?.getList()
                                            const organizationList = list[planIndex].assignOrganizationList[index].organizationList;
                                            if (organizationList && organizationList.length > 0) {
                                                for (let index = 0; index <= organizationList.length; index++) {
                                                    assignOrganizationRef.current?.remove?.(0)
                                                }
                                                assignOrganizationRefAdd.current?.add({
                                                    name: '',
                                                });
                                            }
                                        };
                                        return (
                                            <ProCard
                                                bordered
                                                extra={action}
                                                title={`采访对象${index + 1}`}
                                                style={{
                                                    marginBlockEnd: 8,
                                                }}
                                            >
                                                {listDom}
                                                <ProFormSelect
                                                    width="lg"
                                                    label="单位"
                                                    name="organizationId"
                                                    showSearch
                                                    placeholder="选择单位"
                                                    options={organizationOptions}
                                                    onChange={handleOrganizationChange}
                                                />

                                                <ProFormList
                                                    name="organizationList"
                                                    actionRef={assignOrganizationRef}
                                                    creatorButtonProps={false}
                                                    label={<div style={{ display: 'flex', justifyContent: 'space-between', width: '100vw' }}>
                                                        <span style={{ fontSize: 16 }}>联络人信息</span>
                                                        <Button
                                                            type="primary"
                                                            style={{ display: 'flex', justifyContent: 'flex-end' }}
                                                            onClick={() => {
                                                                assignOrganizationRefAdd.current?.add({
                                                                    name: '',
                                                                });
                                                            }}
                                                        >
                                                            添加联络人信息
                                                        </Button>
                                                    </div>}
                                                >
                                                    <ProFormGroup key="group">
                                                        <ProFormText name="name" label="姓名" width={120} disabled />
                                                        <ProFormText
                                                            name="phone"
                                                            label="电话"
                                                            rules={[
                                                                {
                                                                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                                                    message: '请输入正确的手机号'
                                                                }
                                                            ]}
                                                        />
                                                    </ProFormGroup>
                                                </ProFormList>
                                                <ProFormList
                                                    name="organizationListAdd"
                                                    actionRef={assignOrganizationRefAdd}
                                                    creatorButtonProps={false}
                                                >
                                                    <ProFormGroup key="group">
                                                        <ProFormText name="name" label="姓名" width={120} required rules={[{ required: true, message: '姓名不能为空' }]} />
                                                        <ProFormText
                                                            name="phone"
                                                            label="电话"
                                                            rules={[
                                                                {
                                                                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                                                                    message: '请输入正确的手机号'
                                                                }
                                                            ]}
                                                        />
                                                    </ProFormGroup>
                                                </ProFormList>
                                            </ProCard>
                                        );
                                    }}
                                >

                                </ProFormList>}
                            </div>
                        </ProCard>
                    );
                }}
            >

            </ProFormList>
        </DrawerForm>
    );
};

export default AddTravelArrangements;